package fy.soasso;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.TrustAddressManager;
import com.seeyon.ctp.common.authenticate.sso.SSOTicketManager;
import com.seeyon.ctp.organization.principal.PrincipalManager;
import com.seeyon.ctp.portal.sso.SSOLoginContext;
import com.seeyon.ctp.portal.sso.SSOLoginContextManager;
import com.seeyon.ctp.portal.sso.SSOLoginHandshakeInterface;
import com.seeyon.ctp.signin.manager.SignInManager;
import com.seeyon.ctp.signin.po.SignIn;

public class SSOLoginServlet备份 extends HttpServlet {
	private static final Log log = LogFactory.getLog(SSOLoginServlet备份.class);
	private transient Object object;
	private transient PrincipalManager principalManager;
	private SignInManager ssoManager;
	private static final long serialVersionUID = 1L;
	public SSOLoginServlet备份() {
		this.object = new Object();
		this.principalManager = null;
		this.ssoManager = null;
	}
	public void setSignInManager(SignInManager signInManager) {
		this.ssoManager = signInManager;
	}
	public SignInManager getSignInManager() {
		return this.ssoManager;
	}
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		if (this.principalManager == null)
			this.principalManager = ((PrincipalManager) AppContext.getBean("principalManager"));
		if (this.ssoManager == null)
			this.ssoManager = ((SignInManager) AppContext.getBean("signInManager"));
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		// 向前台提示
		PrintWriter out = resp.getWriter();
		SSOLoginContext ssoLoginContext = null;
		String from = req.getParameter("system");
		String code = req.getParameter("code");
		String signin = req.getParameter("signin");
		// 截取请求地址栏工号
		String queryString = req.getQueryString().substring(4, req.getQueryString().length() - 52);
		//System.out.println(">>>>>>>>>>>" + queryString);
		// System.out.println(">>>>>>>>>>>"+ code+signin);
		// http://10.112.0.209/axistask/code/getTrustCode.jsp?uid=signin&system=OA
		String url = "http://10.112.0.209/axistask/code/getTrustCode.jsp";
		String codeGet = sendGet(url, queryString, from);
		System.out.println("333333333333333333333333" + code);
		System.out.println("222222222222222222222222" + codeGet);
		/*
		 * if(codeGet==null){ out.print("11验证码不正确"); }else{
		 * System.out.println("*****************"+codeGet); if(code!=codeGet){
		 * System.out.println("$$$$$$$"); }else{
		 */
		// StringBuffer path = req.getRequestURL();
		// System.out.println(">>>>>"+ req.getRequestURL());
		// String queryString = req.getQueryString();
		// System.out.println("?????"+req.getQueryString());
		// String fullPath = path + queryString;
		// http://10.112.0.209/axistask/code/getTrustCode.jsp?uid=wpsadmin&system=OA
		/*
		 * System.out.println(">>>>>>>>>>>"+ signin); String
		 * urlStr="http://10.112.0.209/axistask/code/getTrustCode.jsp?"+"uid="+
		 * from+"signin="+signin; // 创建URL对象 URL myURL = new URL(urlStr); //
		 * 创建HttpsURLConnection对象，并设置其SSLSocketFactory对象 HttpsURLConnection
		 * httpsConn = (HttpsURLConnection) myURL.openConnection(); //
		 * 取得该连接的输入流，以读取响应内容 InputStreamReader insr = new
		 * InputStreamReader(httpsConn .getInputStream()); // 读取服务器的响应内容并显示 int
		 * respInt = insr.read(); while (respInt != -1) {
		 * System.out.print((char) respInt); respInt = insr.read(); }
		 */

		/*
		 * if(isBlank(code)){ out.println("code is null"); }else
		 */
	if (isBlank(code)) {
			out.println("信任码不能为空");
		} else if (!code.equals(codeGet)) {
			out.println("信任码不正确");
			// resp.addHeader("SSOError", "code is error.");
			return;
		}
		/*
		 * String token = req.getParameter("token"); if (!isBlank(token)){
		 * String loginName =
		 * (String)ServiceManager.getTokenSessionMap().get(token);
		 * RestUserManager restUserManager =
		 * (RestUserManager)AppContext.getBean("restUserManager"); RestUser user
		 * = restUserManager.getUserByLoginName(loginName);
		 * System.out.println("tokenתrest user��"+user);
		 * 
		 * if (!user.getUserName().equals("app")){
		 * out.println("Token is invalid."); return; } }else {
		 * out.println("Token is null."); return ; }
		 */
		if ((!isBlank(signin)) && (isBlank(from))) {
			ssoLoginContext = signinTo(signin);
		} else if ((isBlank(signin)) && (!isBlank(from))) {
			ssoLoginContext = SSOLoginContextManager.getInstance().getSSOLoginContext(from);
		} else if ((isBlank(signin)) && (isBlank(from))) {
			// out.println("Parameter 'from' is not available.");
			//out.println("参数不正确");
			resp.addHeader("SSOError", "Parameter 'from' is not available.");
			return;
		}
		if (ssoLoginContext == null) {
			// out.println(from + " is not available.");
			//out.println("参数不正确");
			resp.addHeader("SSOError", from + " is not available.");
			return;
		}

		if ((ssoLoginContext.isEnableTrustAddress()) && (!TrustAddressManager.getInstance().isTrustPass(req))) {
			out.println(from + " client ip is untrusted.");
			resp.addHeader("SSOError", from + " client ip is untrusted.");
			return;
		}

		String ticketName = ssoLoginContext.getTicketName();
		String ticket = req.getParameter(ticketName);
		if (isBlank(ticket)) {
			out.println("Parameter '" + ticketName + "' is not available.");
			resp.addHeader("SSOError", "Parameter '" + ticketName + "' is not available.");
			return;
		}
		SSOLoginHandshakeInterface handshake = ssoLoginContext.getHandshake();
		if (handshake == null) {
			out.println("SSOLoginHandshakeInterface is not implements.");
			resp.addHeader("SSOError", "Parameter 'SSOLoginHandshakeInterface is not implements.");
			return;
		}
		String username = null;
		try {
			username = handshake.handshake(ticket);
		} catch (Throwable e) {
			log.error(ssoLoginContext, e);
			out.println("Login fail");
			resp.addHeader("SSOError", e.getMessage());
			return;
		}
		//
		try {
			String tourl = req.getParameter("tourl");
			SSOTicketManager.getInstance().newTicketInfo(ticket, username, from);
			StringBuilder sb = null;
			synchronized (this.object) {
				sb = get2URL(req, ssoLoginContext, ticket, tourl);
			}
			resp.sendRedirect(sb.toString());
		} catch (Throwable e) {
			out.println(e.getMessage());
		}
	}

	private SSOLoginContext signinTo(String param) {
		SignIn ssoInfo = this.ssoManager.findSsoByName(param);
		SSOLoginHandshakeInterface handshake = null;
		try {
			handshake = (SSOLoginHandshakeInterface) Class
					.forName(ssoInfo.getCheckUrl() == null ? null : ssoInfo.getCheckUrl()).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		SSOLoginContext signin = new SSOLoginContext();
		signin.setHandshake(handshake);
		signin.setForward(ssoInfo.getSort().intValue() != 0);
		signin.setTicketName(ssoInfo.getLoginParam() == null ? "ticket" : ssoInfo.getLoginParam());
		return signin;

	}

	private StringBuilder get2URL(HttpServletRequest req, SSOLoginContext ssoLoginContext, String ticket,
			String tourl) {
		StringBuilder sb = new StringBuilder();
		// sb.append("/seeyon/main.do?method=login&ticket=" +
		// URLEncoder.encode(ticket) +
		// "&ssoFrom=" +
		// req.getParameter("from")).append("&login.destination=").append(URLEncoder.encode(req.getParameter("dest")).toString());
		sb.append("/seeyon/main.do?method=login&ticket=" + URLEncoder.encode(ticket) + "&ssoFrom="
				+ req.getParameter("from"));
		sb = urlMosaic(req, ssoLoginContext, tourl, sb);
		return sb;
	}

	private StringBuilder urlMosaic(HttpServletRequest req, SSOLoginContext ssoLoginContext, String tourl,
			StringBuilder sb) {
		String UserLanguage = req.getParameter("login_locale");
		if (UserLanguage != null)
			sb.append("&login_locale=" + UserLanguage);
		String UserAgentFrom = req.getParameter("UserAgentFrom");
		if (UserAgentFrom != null)
			sb.append("&UserAgentFrom=" + UserAgentFrom);
		String des = tourl == null ? ssoLoginContext.getDestination() : tourl;
		if (StringUtils.hasText(des)) {
			sb.append("&");
			sb.append("login.destination");
			sb.append("=");
			sb.append(URLEncoder.encode(des));
			String top = ssoLoginContext.getTopFrameName();
			if (StringUtils.hasText(top)) {
				sb.append("&");
				sb.append("com.seeyon.sso.topframename");
				sb.append("=");
				sb.append(top);
			}
		}
		return sb;
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	private boolean isBlank(String s) {
		return (s == null) || (s.length() == 0);
	}

	public String sendGet(String url, String signin, String system) {
		String result = "";
		try {
			String urlName = url + "?uid=" + signin + "&" + "system=" + system;//
			/// System.out.println("111111111111111111"+urlName);
			// http://10.112.0.209/axistask/code/getTrustCode.jsp?uid=signin&system=OA
			URL U = new URL(urlName);
			// URL U = new
			// URL("http://10.112.0.209/axistask/code/getTrustCode.jsp?uid=084655&system=OA");
			URLConnection connection = U.openConnection();
			connection.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			in.close();
		} catch (Exception e) {
			System.out.println("Helloword！！" + e);
		}
		return result;
	}
}
